<?php

namespace app\common\command;

use app\common\model\Video;
use fast\Http;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class BaiduSeoSubmit extends Command
{

    const _TOKEN_ = 'wo2bXFZK1MFRu0j2';

    const _BASE_URL_ = 'https://www.xcd.icu';

    protected function configure()
    {
        $this->setName('baidu_seo_submit')
            ->setDescription('提交链接到百度');
    }

    public function execute(Input $input, Output $output)
    {
        try {
            $videoModel = new Video();

            $offset = 0;

            $limit = 10;

            while (true) {
                $list = $videoModel->orderRaw('RAND()')->limit($offset, $limit)->select();

                if (!$list) {
                    break;
                }

                $urls = [];

                foreach ($list as $item) {
                    $urls[] = sprintf('%s/index/index/detail/id/%d.html', self::_BASE_URL_, $item['id']);
                }

                $output->info(sprintf('准备提交的条数:%d', count($urls)));

                $ret = json_decode(Http::post(
                    sprintf(
                        "http://data.zz.baidu.com/urls?site=%s&token=%s",
                        self::_BASE_URL_,
                        self::_TOKEN_,
                    ),
                    join("\n", $urls),
                ), true);

                if (isset($ret['error'])) {
                    $output->info(sprintf('提交百度失败[%d]:%s', $ret['error'], $ret['message']));
                    if ($ret['message'] == 'over quota') {
                        break;
                    }
                } else {
                    $output->info(sprintf('提交成功:%s', join(',', $urls)));
                }

                $offset += $limit;
            }

        } catch (\Throwable $exception) {
            $output->error(sprintf("%s[%d]", $exception->getMessage(), $exception->getLine()));
            exit(1);
        }
        $output->info("ok");
    }
}
